package com.example.demo.controller;

import com.example.demo.entify.Order;
import com.example.demo.entify.Record;
import com.example.demo.result.Result;
import com.example.demo.result.ResultFactory;
import com.example.demo.service.OrderService;
import com.example.demo.service.aboveProblemsService;
import com.example.demo.util.R;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@CrossOrigin

public class OrderController {
	@Autowired
	private OrderService orderService;
	@Autowired
	private aboveProblemsService aboveProblemsService;

	@PostMapping("/addolder")
	private Result save(@RequestBody Order order) {
		order.setTime(new Date());
		int i = orderService.addOrder(order);
		int orderId = order.getId();

		return i > 0 ? ResultFactory.buildSuccessFactory(orderId) : ResultFactory.buildFailFactory("添加失败");
	}

	@GetMapping("/findAllOlders")
	public Result findAllOlders() {
		List<Order> olderList = orderService.Allolders();

		return ResultFactory.buildSuccessFactory(olderList);
	}

	@GetMapping("/findAllWorkerOlders")
	public Result findAllWorkerOlders(@RequestParam("username") String username) {
		List<Order> workerOlders = orderService.WorkerOlders(username);
		return ResultFactory.buildSuccessFactory(workerOlders);
	}
	@PostMapping("ReceOlders")
	public Result ReceOlders(@RequestBody Order order) {
		int i = orderService.updateState(order);
		return i > 0 ? ResultFactory.buildSuccessFactory(true) : ResultFactory.buildFailFactory("接单失败");
	}

	@PostMapping("/OldesFinish")
	public Result OldesFinish(@RequestBody Order order) {
		int i = orderService.updateState(order);
		return i > 0 ? ResultFactory.buildSuccessFactory(true) : ResultFactory.buildFailFactory("确认失败");
	}
	@GetMapping("/findAllWorkerOlders2")
	public Result selectOrderState(String worker) {
		List<Order> workerOlders = orderService.WorkerOlders2(worker);
		return ResultFactory.buildSuccessFactory(workerOlders);		
	}
	@PostMapping("/RejectOrder")
	
	public Result RejectOrder(@RequestBody Order order) {
		
		int i =orderService.rejectOrder(order);	
		return i > 0 ? ResultFactory.buildSuccessFactory(true) : ResultFactory.buildFailFactory("拒绝失败");
		
	}
	@PostMapping("/Redistribute")
	public Result Redistribute(@RequestBody Order order) {
		
		int i =orderService.Redistribute(order);
		
		return i > 0 ? ResultFactory.buildSuccessFactory(true) : ResultFactory.buildFailFactory("重新派发失败");
		
	}
	/**
	 * 操作记录
	 */
	
	@RequestMapping("/AddRecord")
	public R AddRecord(@RequestBody Record record) {
			int i = orderService.AddRecord(record);
			return i>0 ? R.ok() :R.error(); 		
	}
	
	@RequestMapping("/listRecord")
	public R listRecord(@RequestParam("orderId") Integer orderId) {
		
			List<Record> list = orderService.list(orderId);
			
			return R.ok().put("list", list);
		
	}
	
	
	
	/**
	 * 文件上传
	 */
	@RequestMapping("/upload")
	public R upload(@RequestParam("picture") MultipartFile picture, HttpServletRequest request) {

		String path = "D://ss";
		File filePath = new File(path);
		if (!filePath.exists() && !filePath.isDirectory()) {

			System.out.println("\"目录不存在，创建目录:\" + filePath");
			filePath.mkdir();
		}
		// 获取原始文件名称(包含格式)
		String originalFileName = picture.getOriginalFilename();

		// 获取文件类型，以最后一个`.`为标识
		String type = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);

		// 获取文件名称（不包含格式）
		String name = originalFileName.substring(0, originalFileName.lastIndexOf("."));

		String fileName = name + "." + type;

		File targetFile = new File(path, fileName);
		try {
			picture.transferTo(targetFile);
			return R.ok().put("fileName", fileName).put("fileAddress", path + "/" + fileName);
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("上传失败");
			e.printStackTrace();
			return R.error();
		}
	}

	/**
	 * 文件删除
	 */
	@RequestMapping("/deleteImg")
	public Result deleteImg(String path) {
		File file = new File(path);
		if (file.exists()) {
			file.delete();
			return ResultFactory.buildResult(0, "图片删除成功",true);
		} else {
			return ResultFactory.buildFailFactory("图片不存在");

		}

	}

	/**
	 * 图片回显
	 */

	@RequestMapping("/viewImg/{orderid}")

	public void getFeedBackPicture(HttpServletResponse response, @PathVariable("orderid") Integer orderid)
			throws Exception {

			Order order = orderService.findOrderByid(orderid);

		  String Path = order.getImgUrl();
		  String realPath="D://ss/"+Path;	

		try {
		
				FileInputStream inputStream = new FileInputStream(realPath);
				int i = inputStream.available();
				// byte数组用于存放图片字节数据
				byte[] buff = new byte[i];
				inputStream.read(buff);
				inputStream.close();
				response.setContentType("image/*");

				OutputStream out = response.getOutputStream();
				out.write(buff);
				// 关闭响应输出流
				out.close();
			
		} catch (FileNotFoundException e) {
			// TODO: handle exception
			System.out.println("无图片");
			e.getMessage();
		}

	}
	
	

}
